import ctypes
import os
import socket
import socketserver

import time


import pymysql
import win32con
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QPixmap

# HOST_IP =socket.gethostname() # 获取本地主机名

# ip_port=("192.168.43.55",19984)
# ip_port=(HOST_IP,19984)

# print(HOST_IP)
from Function import Number_Of_Picture

i = int(Number_Of_Picture()[0]) + 1


def get_host_ip():
    """
    查询本机ip地址
    :return:
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip


class MyServer(socketserver.BaseRequestHandler):


    def TCP_DataInsert(self, Id, Time, Image_dir):
        try:
            conn = pymysql.connect(host='localhost', port=3306, user='root', password="root", db="tab")
            cur = conn.cursor()

            Id = Id
            Image_dir = Image_dir
            Time = Time

            sql1 = "INSERT INTO tab (Mid, Mdate, Mimage) VALUES ('" + Id + "','" + Time + "', '" + Image_dir + "')"
            # sql1 = "INSERT INTO tab  (id,NAME) VALUES ("+id1+",'"+name1+"')"
            # 打印测试
            print(sql1)
            # print(sql2)
            # 执行sql语句，并发送给数据库
            cur.execute(sql1)
            # cur.execute(sql2)
            conn.commit()  # 事务提交数据库
            cur.close()
            conn.close()
        except Exception as e:
            print(e)

    def Save_Image(self, imgData, strtime):
        global i
        strImgFile = str(i) + ".jpg"
        i = i + 1
        Parent_Directory = 'picture'
        Image_dir = "./picture/" + strtime.split(' ')[0]

        print("img file name is ", strImgFile)
        if not os.path.exists(Parent_Directory):
            print("Given file path is not exist.")
            os.mkdir('picture')

        if not os.path.exists(Image_dir):
            print("Given file path is not exist.")
            os.mkdir(Image_dir)
        # Path = "E:" + "\\" + strImgFile
        # 将图片数据保存到本地文件
        Image_File = Image_dir + '/' + strImgFile
        with open(Image_File, 'wb') as f:
            f.write(imgData)
            f.close()
        return Image_File

    def handle(self):
        print("conn is :", self.request)  # conn
        print("addr is :", self.client_address)  # addr

        while True:
            try:
                self.str = self.request.recv(10)
                data = bytearray(self.str)
                '''
                find() 方法检测字符串中是否包含子字符串 str ，
                如果指定 beg（开始） 和 end（结束） 范围，则检查是否包含在指定范围内，
                如果指定范围内如果包含指定索引值，返回的是索引值在字符串中的起始位置。
                如果不包含索引值，返回-1。
                '''
                headIndex = data.find(b'\xff\xaa\xff\xaa')
                print(headIndex)

                if headIndex == 0:

                    H = headIndex + 4
                    T = headIndex + 5
                    allLen = int.from_bytes(data[H:T], byteorder='little')
                    idlen = allLen

                    print("车牌长度 ", idlen)

                    H = T
                    T = T + 1
                    allLen = int.from_bytes(data[H:T], byteorder='little')
                    tlen = allLen
                    print("时间数据长度 ", tlen)

                    H = T
                    T = T + 4
                    allLen = int.from_bytes(data[H:T], byteorder='little')
                    print("数据总长度为", allLen)
                    curSize = 0
                    allData = b''
                    while curSize < allLen:
                        data = self.request.recv(1024)
                        allData += data
                        curSize += len(data)

                    print("recv data len is ", len(allData))
                    # 接收到的数据，前64字节是guid，后面的是图片数据
                    arrGuid = allData[0:64]
                    # 去除guid末尾的0
                    tail = arrGuid.find(b'\x00')
                    arrGuid = arrGuid[0:tail]
                    strGuid = str(int.from_bytes(arrGuid, byteorder='little'))  # for test

                    print("-------------request guid is ", strGuid)

                    id = allData[64:64 + idlen]
                    print(id)
                    strid = id.decode('utf-8')

                    if str(strid) == '#':
                        strid = "请查看图片"
                    print("车牌号是", strid)

                    time1 = allData[64 + idlen:64 + idlen + tlen]
                    print(time1)
                    strtime = time1.decode('utf-8')
                    print("时间是", strtime)

                    imgData = allData[64 + idlen + tlen:]
                    # strImgFile = "2.jpg"
                    # print("img file name is ", strImgFile)
                    # Path="E:"+"\\"+strImgFile
                    # #将图片数据保存到本地文件
                    # with open(Path, 'wb') as f:
                    #     f.write(imgData)
                    #     f.close()
                    # self.TCP_Insert(strtime, '66')
                    Image_dir = self.Save_Image(imgData, strtime)
                    print("保存地址:",Image_dir)
                    self.TCP_DataInsert(strid, strtime, Image_dir)

                    # data = "成功接收数据：车牌号：" + id + "时间：" + strtime + \
                    #        "\n图片保存地址为：" + Image_dir

                    # self.Signal_OneParameter.emit(data)

                    # return(data)

                    print(Image_dir)

                    break
            except Exception as e:
                print(e)
                break

port = 19983
# def MyServer_start(self=None):
class MyServer_start(QThread):
    tcp_signal = pyqtSignal(str,str)  # 值变化信号

    def run(self):
        global port
        try:
            # 这个目前我没弄明白这里写法
            self.handle = ctypes.windll.kernel32.OpenThread(  # @UndefinedVariable
                win32con.PROCESS_ALL_ACCESS, False, int(QThread.currentThreadId()))
        except Exception as e:
            print('get thread handle failed', e)
            self.tcp_signal.emit('重启失败', '请重试!')
        try:
            print('thread id', int(QThread.currentThreadId()))
            ip = get_host_ip()

            port = port + 1

            ip_port = (ip, port)
            print(ip)
            Tip = "IP地址：" + ip + "  端口：" + str(port)
            s = socketserver.ThreadingTCPServer(ip_port, MyServer)
            print("start listen")
            self.tcp_signal.emit('开启成功', Tip)
            s.serve_forever()
        except Exception as e:
            print(e)
            print("失败")
            self.tcp_signal.emit('1', '111')
            print("发送")






if __name__ == "__main__":
    # s = socketserver.ThreadingTCPServer(ip_port, MyServer)
    # print("start listen")
    # s.serve_forever()

    # ip = get_host_ip()
    # print(ip)
    # ip_port = (ip, 19984)
    # MyServer_start()

    _thread = MyServer_start()
    _thread.start()

    print('main id', int(QThread.currentThreadId()))

    time.sleep((10))
    # 关闭线程
    ret = ctypes.windll.kernel32.TerminateThread(  # @UndefinedVariable
        _thread.handle, 0)
    print('终止线程', _thread.handle, ret)
